
/**
 * Date:2022年9月3日下午12:25:20
 * Copyright (c) 2022, www.bwbroad.com All Rights Reserved.
 *
*/

package com.action;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Method;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
 
/**
 * Description: TODO <br/>
 * Date:     2022年9月3日 下午12:25:20 <br/>
 * @author   wangbing	 
 */
public class RPCServerImp implements RPCServer{
	 private static ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
	    
	    private static final HashMap<String, Class> serviceRegistry = new HashMap<String, Class>();

	    private static boolean isRunning = false;

	    private static int port;
	 
	    public  RPCServerImp(int port) {
	        this.port = port;
	    }

	    public void stop() {
	        isRunning = false;
	        executor.shutdown();
	    }
	 
	    public void start() throws IOException {
	        ServerSocket server = new ServerSocket();
	        server.bind(new InetSocketAddress(8088));
	        System.out.println("start server");
	        try {
	            while (true) {
	                // 1.监听客户端的TCP连接，接到TCP连接后将其封装成task，由线程池执行
	                executor.execute(new ServiceTask(server.accept()));
	            }
	        } finally {
	            server.close();
	        }
	    }
	 
	    public void register(Class serviceInterface, Class impl) {
	        serviceRegistry.put(serviceInterface.getName(), impl);
	    }
	 
	    public boolean isRunning() {
	        return isRunning;
	    }
	 
	    public int getPort() {
	        return port;
	    }
	 
	    private static class ServiceTask implements Runnable {
	        Socket client = null;

	        public ServiceTask(Socket client) {
	            this.client = client;
	        }

	        public void run() {
	            ObjectInputStream input = null;
	            ObjectOutputStream output = null;
	            try {
	                // 2.反序列化成对象，
	                input = new ObjectInputStream(client.getInputStream());
	            	TestDTO arguments = (TestDTO) input.readObject();
	            	//2.protoc反序列化
//	         		Math2DTO arguments = Math2DTO.parseFrom(client.getInputStream());
//	                String serviceName = input.readUTF();
//	                String methodName = input.readUTF();
//	                Class<?>[] parameterTypes = (Class<?>[]) input.readObject();
//					
//					  Class serviceClass = serviceRegistry.get(serviceName); if (serviceClass ==
//					  null) { throw new ClassNotFoundException(serviceName + " not found"); }
//					  Method method = serviceClass.getMethod(methodName, parameterTypes); Object
//					  result = method.invoke(serviceClass.newInstance(), arguments);
	                Integer x = arguments.getX();
	                Integer y = arguments.getY();
	                if (x!=null && y!=null) {
	                	Integer result =  x+y;
	                	// 3.将执行结果反序列化，通过socket发送给客户端
	                	output = new ObjectOutputStream(client.getOutputStream());
	                	output.writeObject(result);
					}
	            } catch (Exception e) {
	                e.printStackTrace();
	            } finally {
	                if (output != null) {
	                    try {
	                        output.close();
	                    } catch (IOException e) {
	                        e.printStackTrace();
	                    }
	                }
	                if (input != null) {
	                    try {
	                        input.close();
	                    } catch (IOException e) {
	                        e.printStackTrace();
	                    }
	                }
	                if (client != null) {
	                    try {
	                    	client.close();
	                    } catch (IOException e) {
	                        e.printStackTrace();
	                    }
	                }
	            }
	        }
	    }
	    
}

